Writing Health Category Samples PRO
The Scripting app allows you to write categorical health data to Apple HealthKit using the HealthCategorySample class and the Health.saveCategorySample() method. Category samples represent discrete health-related events or conditions, such as sleep stages, mindful sessions, menstrual flow, ovulation test results, and more.
This guide describes how to create and save a HealthCategorySample.
Prerequisites
-
Confirm that HealthKit is available on the device:
-
Ensure the script has the required permission for the target category type. The Scripting app will automatically request authorization if needed when saving.
1. Create a HealthCategorySample
Use HealthCategorySample.create() to construct a new category sample.
Parameters
type: AHealthCategoryTypestring (e.g.,"sleepAnalysis","mindfulSession","menstrualFlow", etc.).startDate: The beginning of the time interval that the event applies to (JavaScriptDate).endDate: The end of the event’s time interval (JavaScriptDate).value: The integer value representing the state of the category. You must use the corresponding enum value based on the type.metadata(optional): An optional metadata object describing additional attributes.
Value Mapping
The value must be one of the pre-defined category values. For example:
-
For
"sleepAnalysis", use theHealthCategoryValueSleepAnalysisenum:HealthCategoryValueSleepAnalysis.asleepCoreHealthCategoryValueSleepAnalysis.awake- etc.
-
For
"menstrualFlow", useHealthCategoryValueSeverity:HealthCategoryValueSeverity.mild,moderate,severe, etc.
Refer to each category type’s enum definition for valid values.
Example
2. Save the Category Sample
Use Health.saveCategorySample() to save the created sample to HealthKit.
If saving fails (e.g., due to permission denial), the promise will reject with an error.
Full Example
Notes
- The
valuemust be a valid enum for the selectedtype, or the creation will fail. startDateandendDatedefine the time range the event applies to — e.g., a sleep session or a mindful moment.- Metadata is optional but can be useful for tagging data source or context.
